import { BlockEnum, NodePanelProps } from '@/components/workflow/types'
import { INPUT_CONSTRAINTS } from '@/pages/workflow/components/InspectData'
import { useWorkFlowStore } from '@/store/workflowStore'
import { CaretRightOutlined } from '@ant-design/icons'
import { Collapse, Select } from 'antd'
import { cloneDeep } from 'lodash'
import type { FC } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import TextareaWithParamsV2 from '../../components/TextareaWithParamsV2'
import { ComponentDescMap } from '../../constants'
import { useSourceOptions } from '../../hooks/use-source-options'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import '../style.less'
import { InputVar } from '../types'
import ParamList from './components/ParamList'
import { EndNodeType } from './types'

const EndPanel: FC<NodePanelProps<EndNodeType>> = ({ id, data }) => {
  const { setFlowVariables } = useWorkFlowStore()

  const [loadContent, setLoadContent] = useState(false)

  const { options } = useSourceOptions(data)
  const [outputs, setOutputs] = useState(cloneDeep(data.outputs))

  const getSourceOptions = info => {
    return info.outputs
      ? info.outputs.filter(input => input.variable).map(input => ({ value: input.variable, label: input.variable }))
      : []
  }

  const [sourceOptions, setSourceOptions] = useState<{ value: string; label: string }[]>(getSourceOptions(data))

  const handleVarListChange = useCallback(
    (newList: InputVar[]) => {
      const newOutputs = cloneDeep(newList)
      setOutputs(newOutputs)
      setFlowVariables(id, data.title, { outputs: newOutputs })
    },
    [outputs, setOutputs]
  )

  const [outputType, setOutputType] = useState(data.outputType || 'outputs') // # outputs | text
  const [outputText, setOutputText] = useState(data.outputText || '')

  const handleOutputTypeChange = type => {
    console.log('setOutputType   Change', type)
    setOutputType(type)
    setFlowVariables(id, data.title, { outputType: type })
  }
  const handleOutputTextChange = text => {
    console.log('handleOutputText    Change', text)
    setOutputText(text)
    setFlowVariables(id, data.title, { outputText: text })
  }

  useEffect(() => {
    console.log('---------EndPanel options', options)
    setSourceOptions(getSourceOptions(data))
    setLoadContent(true)
  }, [options])

  return (
    <div className="workflow-common-panel">
      <div className="common-panel-desc">{data.desc || ComponentDescMap[BlockEnum.End]}</div>
      <div className="flexRow mb-[8px] justify-between">
        <div className="text-[14px] font-[600]">选择回答模式</div>
        <div>
          <Select
            defaultValue={outputType}
            placeholder="请选择"
            placement="bottomLeft"
            style={{ width: '300px', pointerEvents: 'auto' }}
            onChange={val => handleOutputTypeChange(val)}
            options={[
              { value: 'outputs', label: '返回变量，由智能体生成回答' },
              { value: 'text', label: '直接使用指定内容回答' }
            ]}
          ></Select>
        </div>
      </div>
      {loadContent && (
        <>
          <div className="nodrag cursor-default">
            <Collapse
              bordered={false}
              defaultActiveKey={['1']}
              expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
              className="bg-[#fafafa]"
              items={[
                {
                  key: '1',
                  label: (
                    <CollapseNodeComponent
                      title="输出"
                      tooltipText="变量在智能体调用工作流完成后被输出。“返回变量”模式中，变量会被智能体总结后回复用户；“直接回答”模式中，智能体只会回复设定的“回答内容”"
                    ></CollapseNodeComponent>
                  ),
                  children: (
                    <>
                      <div className="ml-[1px] flex">
                        <div className="input-head w-[32%]">参数名称</div>
                        <div className="input-head w-[28%]">参数值</div>
                      </div>
                      <ParamList
                        readonly={false}
                        list={outputs}
                        info={data}
                        citeOptions={options}
                        outputType= {outputType}
                        onChange={handleVarListChange}
                      />
                    </>
                  )
                }
              ]}
            />
          </div>
          {outputType === 'text' ? (
            <div className="mt-[8px]">
              <Collapse
                bordered={false}
                defaultActiveKey={['2']}
                expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
                className="bg-[#fafafa]"
                items={[
                  {
                    key: '2',
                    label: <CollapseNodeComponent title="指定内容回答"></CollapseNodeComponent>,
                    children: (
                      <>
                        <TextareaWithParamsV2
                          placeholder="填写指定回答，输入'{' 选择变量进行插入。"
                          value={outputText}
                          onChange={msg => {
                            handleOutputTextChange(msg)
                          }}
                          error={
                            !outputText?.length ||
                            !outputText.trim() ||
                            outputText.length > INPUT_CONSTRAINTS.AGENT_RECOVERY_MAX_LENGTH
                          }
                          citeOptions={sourceOptions}
                        />
                        {!outputText?.length && (
                          <div className="custom-params-invalid">{`直接使用指定内容回答时，输出内容不能为空`}</div>
                        )}
                        {outputText.length > INPUT_CONSTRAINTS.AGENT_RECOVERY_MAX_LENGTH && (
                          <div className="custom-params-invalid">{`输出内容不能大于${INPUT_CONSTRAINTS.AGENT_RECOVERY_MAX_LENGTH}个字符`}</div>
                        )}
                      </>
                    )
                  }
                ]}
              />
            </div>
          ) : null}
        </>
      )}
    </div>
  )
}

export default React.memo(EndPanel)
